<?php

namespace app\marketing\controller;

use app\common\controller\Adminbase;
use app\model\DistributionSetting;
use app\model\Goods;
use app\model\GoodsCategory;
use app\model\GoodsContentArticle;
use app\model\GoodsContentCategory;
use app\model\GoodsContentGoods;
use app\model\GoodsType;
use app\service\DeepSeekService;
use util\Logger;

class Content extends Adminbase
{
    public function index()
    {
        return $this->fetch();
    }

    /**
     * 分类列表
     * @return string|\think\response\Json
     * @throws \think\exception\DbException
     */
    public function category()
    {
        $model = 'GoodsContentCategory';

        if ($this->request->isAjax()) {
            $page     = input('page') ? input('page') : 1;
            $pageSize = input('limit') ? input('limit') : 20;

            $list  = GoodsContentCategory::field('*')
                ->page($page, $pageSize)
                ->order('sort', 'asc')
                ->order('id', 'asc')
                ->withAttr('type', function ($value) {
                    return $value == 1 ? '商品' : '图文';
                })
                ->select();
            $total = GoodsContentCategory::count();

            $nav    = new \util\LeftNav();
            $items  = $nav::category($list);
            $result = array("code" => 0, "count" => $total, "data" => $items);
            return json($result);
        }

        //生成列表数据
        $builder = new \app\common\controller\ListBuilder();
        $builder
            ->setDataUrl('category')
            ->setFormUrl('category_form')
            ->setDelAllBtn(false)
            ->setModel($model)
            ->setSwitchTpl('switchTpl', 'status')
            ->setLimit(30)
            ->addTableCheckBox()
            ->addTableColumn('id', 'ID', 80, null, true)
            ->addTableColumn('sort', '排序', 100, null, false, '', false, '', true)
            ->addTableColumn('leftTitle', '分类名称', 200)
            ->addTableColumn('level', '分类级别', 200)
            ->addTableColumn('type', '类型', 150)
            ->addTableColumn('status', '是否显示', 120, '#switchTpl', false, null, false)
            ->addTableOperation('160', false)
            ->returnForm();

        $this->assign('no_title', 1);
        $this->assign('module', 'app');
        return $this->fetch('admin@common/lists');

    }

    /**
     * 添加分类
     */
    public function category_form()
    {
        $model = 'GoodsContentCategory';
        $id    = $this->request->param('id/d');
        if (isset($id) && $id > 0) {
            $info = GoodsContentCategory::find($id);
            $this->assign('id', $id);
            $this->assign('action', 2);
        } else {
            $info = [
                'pid'  => 0,
                'sort' => 50,
                'type' => 1,
            ];
        }
        $category = createTreeNav($model, 'id, pid, title', [['status', 'eq', 1], ['pid', 'eq', 0]], 1, '作为一级分类');

        $builder = new \app\common\controller\FormBuilder();
        $builder
            ->setModel($model)
            ->setSuccessUrl('category')
            ->addFormItem('pid', 'select', '上级分类', '', $category)
            ->addFormItem('title', 'text', '分类名', '', [], 1)
            ->addFormItem('type', 'radio', '类型', '', [1 => '商品', 2 => '图文'], 1)
            ->addFormItem('sort', 'gtnumber', '排序', '值越小排序越靠前')
            ->setFormData($info)
            ->returnForm();

        $this->assign('module', 'app');
        $this->assign('is_verify', 0);
        return $this->fetch('admin@common/form');
    }


    public function goods()
    {
        $model = 'GoodsContentGoods';

        if ($this->request->isAjax()) {
            $map      = $this->buildParamsMap();
            $page     = input('page') ? input('page') : 1;
            $pageSize = input('limit') ? input('limit') : 20;

            $list   = GoodsContentGoods::where($map)
                ->field('*')
                ->with(['goods', 'category'])
                ->withAttr('image', function ($value) {
                    return $value ? get_file_path($value, 1) : '';
                })
                ->withAttr('sale_price', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->withAttr('commission', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->page($page, $pageSize)
                ->order('sort', 'asc')
                ->order('id', 'asc')
                ->select();
            $total  = GoodsContentGoods::where($map)->count();
            $result = ["code" => 0, "count" => $total, "data" => $list];
            return json($result);
        }

        //生成列表数据
        $builder = new \app\common\controller\ListBuilder();
        $builder
            ->setLayerBtn([
                ['title' => '商品配置', 'url' => url('select'), 'class' => '', 'area' => '["95vw", "100vh"]'],
            ])
            ->setConfirmBtn([
                ['title' => 'AI一键生文', 'url' => url('create_share_text'), 'class' => 'layui-btn-normal', 'msg' => '是否一键生成商品分享文案？'],
            ])
            ->setAddBtn(false)
            ->setDelAllBtn(false)
            ->setDataUrl('goods')
            ->setLimit()
            ->setModel($model)
            ->setSwitchTpl('switchTpl', 'status')
            ->setSwitchTpl('amplifyTpl', 'image')
            ->addTableColumn('id', 'ID', null, null, true)
            ->addTableColumn('sort', '排序', null, null, false, '', false, '', true)
            ->addTableColumn('category_name', '素材分类')
            ->addTableColumn('product_id', '商品ID')
            ->addTableColumn('title', '商品标题', 450)
            ->addTableColumn('sale_price', '销售价格', 150)
            ->addTableColumn('commission', '佣金', 150)
            ->addTableColumn('image', '图片', null, '#amplifyTpl')
            ->addTableOperation()
            ->returnForm();

        $this->assign('no_title', 1);
        $this->assign('module', 'app');
        return $this->fetch('admin@common/lists');
    }

    public function create_share_text()
    {
        $api_key = \app\admin\model\Config::where('name', 'ai_key')->value('value');
        if (empty($api_key)) {
            return json(['code' => -1, 'msg' => '请先配置AI密钥']);
        }
        $goods    = GoodsContentGoods::field('g.id, g.title')->alias('cg')
            ->leftJoin('goods g', 'g.id = cg.goods_id')
            ->where('cg.status', 1)
            ->where('g.status', 1)
            ->where('g.share_text', 'eq', '')
            ->select()->toArray();
        $ai_model = new DeepSeekService();
        foreach ($goods as $item) {
            $messages = [
                [
                    'role'    => 'user',
                    'content' => "帮我生成一条关商品分享文案，商品标题为：{$item['title']}\n适当使用 emoji 来增强视觉吸引力和情感表达以及换行，结果只需要正文内容不需要文案建议。"
                ]
            ];
            //
            try {
                $res        = $ai_model->createChatCompletion($messages);
                $share_text = $res['content'];
                if ($share_text) {
                    \app\model\Goods::where('id', $item['id'])->update(['share_text' => $share_text]);
                }
            } catch (\Exception $e) {
                continue;
            }
        }
        return json(['code' => 0, 'msg' => '生成成功']);
    }

    public function select()
    {
        $model = 'Goods';

        if ($this->request->isAjax()) {
            $map      = $this->buildParamsMap();
            $page     = input('page') ? input('page') : 1;
            $pageSize = input('limit') ? input('limit') : 20;

            $list   = Goods::where($map)
                ->withAttr('source', function ($value, $data) {
                    $text = [1 => "<span class='layui-badge layui-bg-blue'>定向</span>", 2 => "<span class='layui-badge layui-bg-orange'>公开</span>"];
                    return $value ? $text[$value] : '';
                })
                ->withAttr('sale_price', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->withAttr('commission', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->withAttr('share_commission', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->withAttr('subsidy_commission', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->withAttr('partners_subsidy_push', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->withAttr('partners_subsidy_shop', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->withAttr('plan_type', function ($value) {
                    $text = [1 => '定向计划', 2 => '公开计划', 3 => '机构定向计划', 4 => '机构普通计划'];
                    return $text[$value] ?? '';
                })
                ->field('*')
                ->page($page, $pageSize)
                ->order('sort asc, id desc')
                ->where('status', 1)
                ->with(['category', 'type'])
                ->select();
            $total  = Goods::where($map)->where('status', 1)->count();
            $result = ["code" => 0, "count" => $total, "data" => $list];
            return json($result);
        }

        $content_category = GoodsContentCategory::where('pid', 'neq', 0)
            ->where('status', 1)
            ->where('type', 1)
            ->order('pid asc, sort asc, id asc')
            ->column('id, title');

        //生成列表数据
        $builder = new \app\common\controller\ListBuilder();
        $builder
            ->setAddBtn(false)
            ->setDelAllBtn(false)
            ->setSelectDataConfirmBtn([
                ['title' => '导入', 'url' => url('import'), 'class' => 'layui-btn-normal', 'msg' => '是否导入选中商品？'],
            ])
            ->setDataUrl('select')
            ->setFormUrl('form')
            ->addExtraItem('category_id', 'select', '素材分类', $content_category)
            ->addSearchItem('title', 'text', '商品标题')
            ->addSearchItem('product_id', 'text', '商品ID')
            ->addSearchItem('shop_appid', 'text', '小店ID')
            ->setLimit()
            ->setModel($model)
            ->addTableCheckBox('left')
            ->setSwitchTpl('switchTpl', 'status')
            ->setSwitchTpl('amplifyTpl', 'image')
            ->addTableColumn('id', 'ID', null, null, true)
            ->addTableColumn('source', '来源', 120)
            ->addTableColumn('plan_type', '计划类型销售价格', 130)
            ->addTableColumn('product_id', '商品ID', 180)
            ->addTableColumn('title', '标题', 450)
            ->addTableColumn('sale_price', '销售价格', 150)
            ->addTableColumn('commission', '佣金', 150)
            ->addTableColumn('image', '图片', null, '#amplifyTpl')
            ->addTableColumn('subsidy_commission', '补贴佣金', 150)
            ->addTableColumn('partners_subsidy_push', '团长推客补贴', 150)
            ->addTableColumn('partners_subsidy_shop', '团长小店补贴', 150)
            ->returnForm();

        $this->assign('module', 'app');
        return $this->fetch('admin@common/lists');
    }

    public function import()
    {
        $ids       = $this->request->param('ids');
        $form_data = $this->request->param('formData');
        $form_arr  = [];
        parse_str($form_data, $form_arr);
        $category_id = $form_arr['category_id'] ?? 0;
        if ($ids) {
            $save = $this->createSaveData($ids, $category_id);
            if ($save) {
                (new GoodsContentGoods())->saveAll($save);
            }
        }
        return json(['code' => 0, 'msg' => '导入成功', 'data' => ['close' => 1]]);
    }

    public function createSaveData(array $goods_ids, int $category_id = 0)
    {
        $db_ids = GoodsContentGoods::where('goods_id', 'gt', 0)->column('goods_id');
        $save   = [];
        foreach ($goods_ids as $goods_id) {
            if (!in_array($goods_id, $db_ids)) {
                $save[] = [
                    'goods_id'     => $goods_id,
                    'category_id'  => $category_id,
                    'comment_text' => '👇点击下方链接下单：{推广链接}',
                ];
            }
        }
        return $save;
    }

    public function setting()
    {
        $uuid = 'content';
        $info = DistributionSetting::where('uuid', $uuid)->find();
        if (empty($info)) {
            $info = [
                'uuid'  => $uuid,
                'name'  => '发圈设置',
                'type'  => 0,
                'value' => json_encode(['scroll' => 0]),
            ];
            DistributionSetting::create($info);
        } else {
            $info['value'] = json_decode($info['value'], true);
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            $save = [
                'title'  => $data['title'],
                'image'  => $data['image'],
                'scroll' => $data['scroll'] ?? 0,
            ];
            DistributionSetting::where('uuid', $uuid)->update([
                'value' => json_encode($save, JSON_UNESCAPED_UNICODE),
            ]);
            return json(['code' => 0, 'msg' => '保存成功', 'data' => ['close' => 1]]);
        }

        $builder = new \app\common\controller\FormBuilder();
        $builder
            ->setUrl('setting')
            ->setSuccessUrl()
            ->addFormItem('title', 'text', '网络昵称')
            ->addFormItem('image', 'image', '头像设置')
//            ->addFormItem('scroll', 'radio', '发圈滚动', '', [0 => '关闭', 1 => '开启'])
            ->setFormData($info['value'])
            ->returnForm();

        $this->assign('no_title', 1);
        $this->assign('no_return', 1);
        $this->assign('module', 'app');
        $this->assign('is_verify', 0);
        return $this->fetch('admin@common/form');
    }

    /**
     * 图文列表
     * @return string|\think\response\Json
     * @throws \think\exception\DbException
     */
    public function article()
    {
        $model = 'GoodsContentArticle';

        if ($this->request->isAjax()) {
            $page     = input('page') ? input('page') : 1;
            $pageSize = input('limit') ? input('limit') : 20;

            $list  = GoodsContentArticle::field('*')
                ->page($page, $pageSize)
                ->with(['category'])
                ->order('sort', 'asc')
                ->order('id', 'asc')
                ->select();
            $total = GoodsContentArticle::count();

            $result = array("code" => 0, "count" => $total, "data" => $list);
            return json($result);
        }

        //生成列表数据
        $builder = new \app\common\controller\ListBuilder();
        $builder
            ->setDataUrl('article')
            ->setFormUrl('article_form')
            ->setDelAllBtn(false)
            ->setModel($model)
            ->setSwitchTpl('switchTpl', 'status')
            ->setLimit(30)
            ->addTableCheckBox()
            ->addTableColumn('id', 'ID', 80, null, true)
            ->addTableColumn('sort', '排序', 100, null, false, '', false, '', true)
            ->addTableColumn('category_name', '素材分类', 150)
            ->addTableColumn('title', '标题', 200)
            ->addTableColumn('status', '是否显示', 120, '#switchTpl', false, null, false)
            ->addTableOperation('160', false)
            ->returnForm();

        $this->assign('no_title', 1);
        $this->assign('module', 'app');
        return $this->fetch('admin@common/lists');

    }

    /**
     * 添加图文
     */
    public function article_form()
    {
        $model = 'GoodsContentArticle';
        $id    = $this->request->param('id/d');
        if (isset($id) && $id > 0) {
            $info = GoodsContentArticle::find($id);
            $this->assign('id', $id);
            $this->assign('action', 2);
        } else {
            $info = [
                'sort' => 50,
            ];
        }
        $content_category = GoodsContentCategory::where('pid', 'neq', 0)
            ->where('status', 1)
            ->where('type', 2)
            ->order('pid asc, sort asc, id asc')
            ->column('id, title');

        $builder = new \app\common\controller\FormBuilder();
        $builder
            ->setModel($model)
            ->setSuccessUrl('article')
            ->addFormItem('category_id', 'select', '素材分类', '', $content_category)
            ->addFormItem('title', 'text', '标题', '', [], 1)
            ->addFormItem('content', 'textarea', '内容', '', [], 1)
            ->addFormItem('images', 'images', '图片')
            ->addFormItem('sort', 'gtnumber', '排序', '值越小排序越靠前')
            ->setFormData($info)
            ->returnForm();

        $this->assign('module', 'app');
        $this->assign('is_verify', 0);
        return $this->fetch('admin@common/form');
    }

}
